package com.ruoyi.feike.service.impl;

import java.io.*;
import java.util.*;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.activiti.service.impl.ActTaskServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.InstanceIdUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.domain.vo.VehicleContract;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.BookmarksNavigator;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.feike.service.IContractApprovalService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * feikeService业务层处理
 *
 * @author ruoyi
 * @date 2022-09-06
 */
@Service
@Slf4j
public class ContractApprovalServiceImpl implements IContractApprovalService
{
    @Autowired
    private ContractApprovalMapper contractApprovalMapper;

    @Autowired
    private ContractRecordMapper contractRecordMapper;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    @Autowired
    private DealercodeContractFilingMapper dealercodeContractFilingMapper;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private InstanceIdUtil instanceIdUtil;

    @Autowired
    private NotesMapper notesMapper;

    @Autowired
    private ActTaskServiceImpl actTaskService;

    @Autowired
    private BasicContractMapper basicContractMapper;

    @Autowired
    private DealerInformationMapper dealerInformationMapper;

    @Autowired
    private DealerSectorContractgroupMapper dealerSectorContractgroupMapper;

    @Autowired
    private IAnnualReviewyService annualReviewyService;


    /**
     * 查询feike
     *
     * @param id feikeID
     * @return feike
     */
    @Override
    public ContractApproval selectContractApprovalById(String id)
    {
        return contractApprovalMapper.selectContractApprovalById(id);
    }

    /**
     * 查询feike列表
     *
     * @param contractApproval feike
     * @return feike
     */
    @Override
    public List<ContractApproval> selectContractApprovalList(ContractApproval contractApproval)
    {
        return contractApprovalMapper.selectContractApprovalList(contractApproval);
    }

    /**
     * 新增feike
     *
     * @param map feike
     * @return 结果
     */
    @Override
    @Transactional
    public int insertContractApproval(Map<String, Object> map){
        log.info("试用车抵押合同的map={}",map);
        String currentVal = instanceIdUtil.getRedisInstanceId("CA");
        String instanceId = instanceIdUtil.getIstanceId("CA", currentVal);
        Notes notes = new Notes();
        notes.setComments((String)map.get("comments"));
        notes.setId(IdUtils.simpleUUID());
        notes.setInstanceId(instanceId);
        notesMapper.insertNotes(notes);
        String title = "";
        if (StringUtils.isNotNull(map.get("name"))) {
            title = String.valueOf(map.get("name"));
        } else {
            title = "Contract Approval";
        }

        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                .getUser()
                .getUserId()
                .toString());
        //流程开始
        ProcessInstance processInstance = null;
        Task task = null;
        if(map.get("caoGao") != null && map.get("caoGao").toString().equals("1")){
            //草稿行为,不发流程，仅保存
        }else{
            if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey(map.get("processDefinitionKey") + "")
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            } else {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey("contractApproval")
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            }


            task = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getId())
                    .singleResult();



            TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
            List<Task> todoList = query.list();//获取申请人的待办任务列表
            for (Task tmp : todoList) {
                if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                    task = tmp;//获取当前流程实例，当前申请人的待办任务
                    break;
                }
            }
            HashMap<String, Object> variables = new HashMap<String, Object>();
//            List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
//            for (Map<String, Object> form : actForm) {
//                variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
//            }
            variables.put("toUnderwriter", 0);
            taskService.complete(task.getId(), variables);



        }


        AnnualReviewy annualReviewy = new AnnualReviewy();
        annualReviewy.setId(IdUtils.simpleUUID());
        annualReviewy.setTitle(title);
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setInstanceId(instanceId);
        annualReviewy.setState("0");
        if(map.get("caoGao") != null && map.get("caoGao").toString().equals("1")){//草稿行为时
            annualReviewy.setState("3");
        }
        if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
            annualReviewy.setType(map.get("processDefinitionKey") + "");
        } else {
            annualReviewy.setType("annualVerification");
        }
        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        Map<String, Object> contractApproval1 = (Map<String, Object>) map.get("contractApproval");

//        ContractApproval contractApproval2 = JSONObject.parseObject(contractApproval1.toString(), ContractApproval.class);
//        log.info("当前传业contractApproval业务参数对象contractApproval={}",contractApproval2);
//        if(Objects.isNull(contractApproval2)){
//            log.info("contractApproval为空,不做业务处理");
//        }



        // 添加业务参数
        ContractApproval contractApproval = new ContractApproval();
        contractApproval.setId(IdUtils.simpleUUID());
        contractApproval.setDealerCode(String.valueOf(contractApproval1.get("dealerCode")));
        contractApproval.setDealerName(String.valueOf(contractApproval1.get("dealerName")));
        contractApproval.setSector(String.valueOf(contractApproval1.get("sector")));
        contractApproval.setFileUrl(String.valueOf(contractApproval1.get("fileUrl")));
        contractApproval.setGroupName(String.valueOf(contractApproval1.get("groupName")));
        contractApproval.setFileName(String.valueOf(contractApproval1.get("fileName")));
        contractApproval.setInstanceId(instanceId);
        contractApproval.setCreateTime(new Date());
        contractApproval.setUpdateTime(new Date());
        contractApprovalMapper.insertContractApproval(contractApproval);
        annualReviewyService.saveDbLog("1","新增流程","新增自发合同表单" ,instanceId,null,contractApproval,null);
        String dealerName = String.valueOf(contractApproval1.get("dealerName"));
        List<DealerInformation> dealerNameByCode = dealerInformationMapper.getDealerNameByName(dealerName);
        BasicInformation basicInformation = new BasicInformation();
        basicInformation.setId(IdUtils.simpleUUID());
        basicInformation.setDealerNameEN(dealerNameByCode.get(0).getEnName());
        basicInformation.setDealerNameCN(dealerNameByCode.get(0).getDealerName());
        basicInformation.setSector(String.valueOf(contractApproval1.get("sector")));
        basicInformation.setInstanceId(instanceId);
        basicInformation.setGroupNameEN(dealerNameByCode.get(0).getGroupName());
        basicInformation.setGroupNameCN(dealerNameByCode.get(0).getGroupNameCN());
        basicInformationMapper.insertBasicInformation(basicInformation);
        if(ObjectUtil.isNotEmpty(task)){
            annualReviewy.setStartNode(task.getName());
        }
        int i = annualReviewyMapper.insertAnnualReviewy(annualReviewy);

        //非草稿行为，提交流程 发送邮件
        if(map.get("caoGao") == null || !map.get("caoGao").toString().equals("1")){
            //发送邮件
            try {
                org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
                org.activiti.engine.task.Task task1 = taskService.createTaskQuery()
                        .processInstanceId(processInstanceMe.getProcessInstanceId())
                        .singleResult();

                ThreadUtil.execute(new Runnable() {

                    @Override
                    public void run() {
                        actTaskService.sendMail(task1, instanceId,"");
                    }
                });

            } catch (Exception e) {
                log.error("邮件发送失败，{}",e.getMessage());
            }
        }
        return i;
    }


    @Override
    @Transactional
    public int insertContractApprovalList(Map<String, Object> map) {
        List<Map<String, Object>> mapList = (List<Map<String, Object>>) map.get("contractApproval");
        for (Map<String, Object> contractApproval1 : mapList) {



        log.info("试用车抵押合同的map={}",map);
        String currentVal = instanceIdUtil.getRedisInstanceId("CA");
        String instanceId = instanceIdUtil.getIstanceId("CA", currentVal);
        String title = "";
        if (StringUtils.isNotNull(map.get("name"))) {
            title = String.valueOf(map.get("name"));
        } else {
            title = "Contract Approval";
        }

        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                .getUser()
                .getUserId()
                .toString());
        //流程开始
        ProcessInstance processInstance = null;
        Task task = null;
        if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
            processInstance = processRuntime.start(ProcessPayloadBuilder
                    .start()
                    .withProcessDefinitionKey(map.get("processDefinitionKey") + "")
                    .withName(title)
                    .withBusinessKey(instanceId)
                    // .withVariable("deptLeader",join)
                    .build());
        } else {
            processInstance = processRuntime.start(ProcessPayloadBuilder
                    .start()
                    .withProcessDefinitionKey("contractApproval")
                    .withName(title)
                    .withBusinessKey(instanceId)
                    // .withVariable("deptLeader",join)
                    .build());
        }


        task = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();



        TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
        List<Task> todoList = query.list();//获取申请人的待办任务列表
        for (Task tmp : todoList) {
            if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                task = tmp;//获取当前流程实例，当前申请人的待办任务
                break;
            }
        }
        HashMap<String, Object> variables = new HashMap<String, Object>();
//            List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
//            for (Map<String, Object> form : actForm) {
//                variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
//            }
        variables.put("toUnderwriter", 0);
        taskService.complete(task.getId(), variables);




        AnnualReviewy annualReviewy = new AnnualReviewy();
        annualReviewy.setId(IdUtils.simpleUUID());
        annualReviewy.setTitle(title);
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setInstanceId(instanceId);
        annualReviewy.setState("0");
        if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
            annualReviewy.setType(map.get("processDefinitionKey") + "");
        } else {
            annualReviewy.setType("contractApproval");
        }
        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());

//        ContractApproval contractApproval2 = JSONObject.parseObject(contractApproval1.toString(), ContractApproval.class);
//        log.info("当前传业contractApproval业务参数对象contractApproval={}",contractApproval2);
//        if(Objects.isNull(contractApproval2)){
//            log.info("contractApproval为空,不做业务处理");
//        }



        // 添加业务参数
        ContractApproval contractApproval = new ContractApproval();
        contractApproval.setId(IdUtils.simpleUUID());
        contractApproval.setDealerCode(String.valueOf(contractApproval1.get("dealerCode")));
        contractApproval.setDealerName(String.valueOf(contractApproval1.get("dealerName")));
        contractApproval.setSector(String.valueOf(contractApproval1.get("sector")));
        contractApproval.setFileUrl(String.valueOf(contractApproval1.get("fileUrl")));
        contractApproval.setGroupName(String.valueOf(contractApproval1.get("groupName")));
        contractApproval.setFileName(String.valueOf(contractApproval1.get("fileName")));
        contractApproval.setContractNumber(String.valueOf(contractApproval1.get("contractNumber")));
        contractApproval.setInstanceId(instanceId);
        contractApproval.setCreateTime(new Date());
        contractApproval.setUpdateTime(new Date());
        contractApprovalMapper.insertContractApproval(contractApproval);
        annualReviewyService.saveDbLog("1","新增流程","新增自发合同表单" ,instanceId,null,contractApproval,null);


        String dealerName = String.valueOf(contractApproval1.get("dealerName"));
        List<DealerInformation> dealerNameByCode = dealerInformationMapper.getDealerNameByName(dealerName);
        BasicInformation basicInformation = new BasicInformation();
        basicInformation.setId(IdUtils.simpleUUID());
        basicInformation.setDealerNameEN(dealerNameByCode.get(0).getEnName());
        basicInformation.setDealerNameCN(dealerNameByCode.get(0).getDealerName());
        basicInformation.setSector(String.valueOf(contractApproval1.get("sector")));
        basicInformation.setInstanceId(instanceId);
        basicInformation.setGroupNameEN(dealerNameByCode.get(0).getGroupName());
        basicInformation.setGroupNameCN(dealerNameByCode.get(0).getGroupNameCN());
        basicInformationMapper.insertBasicInformation(basicInformation);

        ContractRecord contractRecord = new ContractRecord();
        contractRecord.setSector(contractApproval.getSector());
        contractRecord.setScenario("Demo Mortgage");
        contractRecord.setLimitType("Demo");
        contractRecord.setDealername(contractApproval.getDealerName());
        contractRecord.setContracttype("试乘试驾车抵押合同");
        contractRecord.setInstanceid(instanceId);
        contractRecord.setIssuedate(new Date());
        contractRecord.setContractno(contractApproval.getContractNumber());
        DealerInformation dealerInfo = new DealerInformation();
        dealerInfo.setDealerName(contractApproval.getDealerName());
        dealerInfo.setMake(contractApproval.getSector());
        List<DealerInformation> dealerInformationsnew = dealerInformationMapper.selectDealerInformationList(dealerInfo);
        if(CollectionUtil.isNotEmpty(dealerInformationsnew)){
            if(dealerInformationsnew.get(0).getGroupName()!=null){
                contractRecord.setGroupName(dealerInformationsnew.get(0).getGroupName());
            }
            if(dealerInformationsnew.get(0).getDealerCode()!=null){
                contractRecord.setDealercode(dealerInformationsnew.get(0).getDealerCode());
            }
            contractRecord.setOemdealercode(dealerInformationsnew.get(0).getDealerCodeFromManufacturer());
        }
        contractRecordMapper.insertContractRecord(contractRecord);
        contractRecordMapper.insertContractRecordThree(contractRecord);
        annualReviewyService.saveDbLog("1","新增流程","新增自发合同报表" ,instanceId,null,contractRecord,null);
        //添加记录
        DealerSectorContractgroup shiJiaChe = new DealerSectorContractgroup();
        shiJiaChe.setDealername(contractApproval.getDealerName());
        shiJiaChe.setSector(contractApproval.getSector());
        shiJiaChe.setContractname("试乘试驾车抵押合同（E已更改）");
        if(!StringUtils.isEmpty(contractApproval.getContractNumber())){
            if(contractApproval.getContractNumber().contains("-M-")){
                shiJiaChe.setContractnumber(contractApproval.getContractNumber());
            }else{
                shiJiaChe.setContractnumber(contractApproval.getContractNumber()+"-1");
            }
        }
        shiJiaChe.setExpDate(DateUtils.getDate());
        shiJiaChe.setDealerCode(contractRecord.getDealercode());
        dealerSectorContractgroupMapper.insertDealerSectorContractgroup(shiJiaChe);
            if(ObjectUtil.isNotEmpty(task)){
            annualReviewy.setStartNode(task.getName());
        }
            int i = annualReviewyMapper.insertAnnualReviewy(annualReviewy);
            annualReviewyService.saveDbLog("1","新增流程",null ,instanceId,null,annualReviewy,null);


            //非草稿行为，提交流程 发送邮件
        if(map.get("caoGao") == null || !map.get("caoGao").toString().equals("1")){
            //发送邮件
            try {
                org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
                org.activiti.engine.task.Task task1 = taskService.createTaskQuery()
                        .processInstanceId(processInstanceMe.getProcessInstanceId())
                        .singleResult();

                ThreadUtil.execute(new Runnable() {

                    @Override
                    public void run() {
                        actTaskService.sendMail(task1, instanceId,null);
                    }
                });

            } catch (Exception e) {
                log.error("邮件发送失败，{}",e.getMessage());
            }
        }
        }
        return 1;
    }

    /**
     * 修改feike
     *
     * @param contractApproval feike
     * @return 结果
     */
    @Override
    public int updateContractApproval(ContractApproval contractApproval)
    {
        contractApproval.setUpdateTime(DateUtils.getNowDate());
        return contractApprovalMapper.updateContractApproval(contractApproval);
    }


    /**
     * 根据instanceId 修改feike
     *
     * @param contractApproval feike
     * @return 结果
     */
    @Override
    public int updateContractApprovalByInstanceId(ContractApproval contractApproval)
    {
        contractApproval.setUpdateTime(DateUtils.getNowDate());
        return contractApprovalMapper.updateContractApprovalByInstanceId(contractApproval);
    }

    /**
     * 批量删除feike
     *
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    public int deleteContractApprovalByIds(String[] ids)
    {
        return contractApprovalMapper.deleteContractApprovalByIds(ids);
    }

    /**
     * 删除feike信息
     *
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteContractApprovalById(String id)
    {
        return contractApprovalMapper.deleteContractApprovalById(id);
    }

    @Override
    public ContractApproval getInfoByInstanceId(String instanceId) {
        ContractApproval contractApproval = contractApprovalMapper.getInfoByInstanceId(instanceId);
        DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
        dealercodeContractFiling.setSubProcessId(instanceId);
        dealercodeContractFiling.setDealerNameCN(contractApproval.getDealerName());
        dealercodeContractFiling.setSector(contractApproval.getSector());
        List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(dealercodeContractFiling);
        if(dealercodeContractFilings!=null && dealercodeContractFilings.size()>0){
            contractApproval.setPdffileUrl(dealercodeContractFilings.get(0).getContractLocation());
            contractApproval.setPdfFileName(dealercodeContractFilings.get(0).getContractName());
        }
        return contractApproval;

    }

    @Override
    public List<BasicContract> generateContract(List<VehicleContract> vehicleContracts) {
        ArrayList<BasicContract> resultList = new ArrayList<>();
        int numberMax = 0 ;
        boolean flag = false;
        if(vehicleContracts.size()>1){
            //记录号码
            flag = true;
        }
        for (VehicleContract vehicleContract : vehicleContracts) {

            List<BasicContract> basicContracts = null;
            try {
                basicContracts = basicContractMapper.selectBasicContractBySector(vehicleContract.getSector());
                if(CollectionUtils.isEmpty(basicContracts)){
                    throw  new BaseException("未配置该品牌合同模板");
                }
                String contractlocation = basicContracts.get(0).getContractlocation();
                if(StringUtils.isEmpty(contractlocation)){
                    throw  new BaseException("未配置该品牌合同模板");
                }
                //加载包含书签的Word文档
                Document doc = new Document();
                doc.loadFromFile(RuoYiConfig.getProfile() + contractlocation);
                //定位到指定书签位置
                BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);

                //用文本内容替换原有书签位置的文本，新替换的内容与原文格式一致
                bookmarksNavigator.moveToBookmark("DealerName");
                bookmarksNavigator.replaceBookmarkContent(vehicleContract.getDealerName(),true);
                bookmarksNavigator.moveToBookmark("DealerName1");
                bookmarksNavigator.replaceBookmarkContent(vehicleContract.getDealerName(),true);
                //签署合同日期
                bookmarksNavigator.moveToBookmark("签署合同日期");
                bookmarksNavigator.replaceBookmarkContent(DateUtils.datePathCn(),true);
                //DEMO抵押合同车辆品牌
                bookmarksNavigator.moveToBookmark("DEMO抵押合同车辆品牌");
                bookmarksNavigator.replaceBookmarkContent(vehicleContract.getSector(),true);
                //经销商法人
                //获取法人中文名
                DealerInformation dealerInformation = dealerInformationMapper.selectInfoBySectorAndDealerName(vehicleContract.getSector(), vehicleContract.getDealerName());
                if(ObjectUtil.isNotNull(dealerInformation)){
                    bookmarksNavigator.moveToBookmark("经销商法人");
                    bookmarksNavigator.replaceBookmarkContent(StringUtils.isEmpty(dealerInformation.getLegalRepresentativeCN())?"":dealerInformation.getLegalRepresentativeCN(),true);
                }
                DealerSectorContractgroup sectorContractGroup = new DealerSectorContractgroup();
                sectorContractGroup.setDealername(vehicleContract.getDealerName());
                sectorContractGroup.setSector(vehicleContract.getSector());
                sectorContractGroup.setContractname("人民币循环贷款合同");

                DealerSectorContractgroup sectorContractGroupDemo = new DealerSectorContractgroup();
                sectorContractGroupDemo.setDealername(vehicleContract.getDealerName());
                sectorContractGroupDemo.setSector(vehicleContract.getSector());
                sectorContractGroupDemo.setContractname("试乘试驾车贷款合同");

                DealerSectorContractgroup shiJiaChe = new DealerSectorContractgroup();
                shiJiaChe.setDealername(vehicleContract.getDealerName());
                shiJiaChe.setSector(vehicleContract.getSector());
                shiJiaChe.setContractname("试乘试驾车抵押合同（E已更改）");

                //List<DealerSectorContractgroup> contractRMB = dealerSectorContractgroupMapper.getContractGroup(sectorContractGroup);
                List<DealerSectorContractgroup> contractDemo = dealerSectorContractgroupMapper.getContractGroup(sectorContractGroupDemo);
                if(CollectionUtil.isEmpty(contractDemo) || CollectionUtil.isEmpty(contractDemo)){
                    throw  new BaseException("未找到Demo主合同,无法生成Demo抵押合同");
                }
                //合同号
                String contractNumber = "";
                //合同号M
                String contractNumberM = "";
                if(CollectionUtil.isNotEmpty(contractDemo)){
                    //最大数
                    String maxS = dealerSectorContractgroupMapper.selectMaxSerialNumber(shiJiaChe);
                    if(flag && numberMax>0){
                        maxS = String.valueOf(numberMax);
                    }
                    DealerSectorContractgroup contractRm1= contractDemo.get(0);

                    if(StringUtils.isEmpty(maxS) || maxS.equals("")){
                        contractNumberM = contractRm1.getContractnumber()+"-M";
                    }else {
                        String max = String.valueOf(Double.valueOf(maxS).intValue());
                        if("1".equals(max)){
                            max ="2";
                        }
                        contractNumberM = contractRm1.getContractnumber()+"-M-"+max;
                    }
                    contractNumber = contractRm1.getContractnumber();
                }
/*                else if(CollectionUtil.isNotEmpty(contractRMB)){
                    //最大数
                    String maxS = dealerSectorContractgroupMapper.selectMaxSerialNumber(shiJiaChe);
                    if(flag && numberMax>0){
                        maxS = String.valueOf(numberMax);
                    }
                    DealerSectorContractgroup contractRm1= contractRMB.get(0);

                    if(StringUtils.isEmpty(maxS) || maxS.equals("")){
                        contractNumberM = dealerInformation.getDealerCode()+"DEMO"+contractRm1.getContractnumber().split("F")[1]+"-M";
                    }else {
                        String max = String.valueOf(Double.valueOf(maxS).intValue());
                        if("1".equals(max)){
                            max ="2";
                        }
                        contractNumberM = dealerInformation.getDealerCode()+"DEMO"+contractRm1.getContractnumber().split("F")[1]+"-M-"+max;
                    }

                    contractNumber = dealerInformation.getDealerCode()+"DEMO"+contractRm1.getContractnumber().split("F")[1];
                }*/
                if(flag && numberMax == 0 ){
                    //记录第一次max
                    if(contractNumberM.contains("-M-")){
                        //说明大于1
                        String num = contractNumberM.substring(contractNumberM.length() - 1);
                        numberMax = Integer.parseInt(num);
                    }else{
                        //说明等于1
                        numberMax = 1 ;
                    }
                }

                //DEMO抵押合同合同号 书签写入
                bookmarksNavigator.moveToBookmark("DEMO抵押合同合同号");
                bookmarksNavigator.replaceBookmarkContent(contractNumberM,true);

                //DEMO抵押合同合同号1
                bookmarksNavigator.moveToBookmark("DEMO抵押合同合同号1");
                bookmarksNavigator.replaceBookmarkContent(contractNumberM,true);

                //ContractNumberD
                bookmarksNavigator.moveToBookmark("ContractNumberD");
                bookmarksNavigator.replaceBookmarkContent(contractNumber,true);

                //DEMO抵押合同车架号
                bookmarksNavigator.moveToBookmark("DEMO抵押合同车架号");
                bookmarksNavigator.replaceBookmarkContent(StringUtils.isNotEmpty(vehicleContract.getVin())?vehicleContract.getVin():"",true);

                //DEMO抵押合同抵押物金额
                bookmarksNavigator.moveToBookmark("DEMO抵押合同抵押物金额");
                bookmarksNavigator.replaceBookmarkContent(StringUtils.isNotEmpty(vehicleContract.getAmount())?vehicleContract.getAmount():"",true);

                //DEMO抵押合同数量
               bookmarksNavigator.moveToBookmark("DEMO抵押合同数量");
               bookmarksNavigator.replaceBookmarkContent("1",true);

                //DEMO抵押合同颜色
                bookmarksNavigator.moveToBookmark("DEMO抵押合同颜色");
                bookmarksNavigator.replaceBookmarkContent(StringUtils.isNotEmpty(vehicleContract.getColor())?vehicleContract.getColor():"",true);

                //经销商法人
//            bookmarksNavigator.moveToBookmark("经销商法人");
//            bookmarksNavigator.replaceBookmarkContent(StringUtils.isNotEmpty(legalPerson)?legalPerson:"",true);

                //文件名
                String fileName = IdUtils.simpleUUID();
                String filePath = "/"+RuoYiConfig.getProfile()+"/profile/template/"+vehicleContract.getSector()+"/"+fileName+".docx";
/*                File file = new File(filePath);
                 if(FileUtil.isEmpty(file)){
                    FileUtil.cleanEmpty(file);
                 }*/

                //保存文档FileFormat.Docx_2013
                doc.saveToFile(filePath, FileFormat.Docx_2013);
                doc.dispose();

                //重新读取生成的文档
                InputStream is = new FileInputStream(filePath);
                XWPFDocument document = new XWPFDocument(is);
                //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
                document.removeBodyElement(0);
                //输出word内容文件流，新输出路径位置
                OutputStream os=new FileOutputStream(filePath);
                document.write(os);
                os.flush();
                os.close();
                document.close();
                BasicContract basicContract = basicContracts.get(0);
                basicContract.setContractlocation("/profile/template/"+vehicleContract.getSector()+"/"+fileName+".docx");
                basicContract.setContractname(vehicleContract.getDealerName()+"_试驾车抵押合同"+".docx");
                basicContract.setContractNumber(contractNumberM);
                resultList.add(basicContract);

            } catch (IOException e) {
                e.printStackTrace();
            }
            if(flag){
                numberMax++;
            }
        }
        return resultList;
    }



    public static void main(String[] args) {
//        String a = "{dealerCode=1, dealerName=绵阳意菲汽车销售服务有限公司, sector=CHRYSLER, fileUrl=http://172.16.10.103:8080/profile/upload/2022/09/09/7dad6a91-0a6b-4a88-bf04-feee7481d732.docx}";
//        String s = JSON.toJSONString(a);
//        JSONObject jsonObject = JSONObject.parseObject(a);
//        System.out.println(jsonObject);
//        String versionInfoStr = jsonObject.getString("versionInfo");
////        VersionInfo versionInfo = JSONObject.parseObject(versionInfoStr, VersionInfo.class);
//
//        ContractApproval contractApproval2 = JSONObject.parseObject(jsonObject.toJSONString(), ContractApproval.class);

    }
}
